<template>
  <div>
    <div v-if="isOneself && programme">
      <van-overlay v-if="visibleModal" :class="recognitionSuc?'overlay':'overlay'" :show="visibleModal" @click="show = false">
        <div style="width: 320px;margin:auto;background: #fff;margin-top:80px;border-radius: 5px;">
            <p class="title">{{$t('face_recognition_check_in')}}</p>
            <div class="wrapper"  style="padding:20px 10px;" @click.stop>
                <div id="fa" class="video-box" :style="'width: ' + screenWidth + 'px; height: ' + clientHeight + 'px;'">
                    <video id="video" :width="screenWidth" :height="clientHeight" preload autoplay loop muted playsinline="true" webkik-playsinline="true">
                    </video>
                    <canvas id="canvas" :width="screenWidth" :height="clientHeight"></canvas>
                </div>
                <canvas id="screenshotCanvas" :width="screenWidth" :height="clientHeight"></canvas>
                <div v-if="!recognitionSuc" style="padding-top: 20px;text-align: center;">{{$t("tips1_recognition_check_in")}}</div>
                <div v-else>
                    <div style="padding-top: 20px;text-align: center;color:#F59A23">{{$t("tips2_please_recognition")}}</div>
                    <div style="text-align:center;margin-top:15px">
                        <van-button round type="default" size="small" style="margin-right: 30px;padding: 0 20px;" @click="cancelDistinguish">{{$t("circle_kg_13")}}</van-button>
                        <van-button round type="primary" size="small" @click="reIdentification">{{$t("Re_identification")}}</van-button>
                    </div>
                </div>
            </div>
        </div>
      </van-overlay>
    </div>
  </div>
</template>

<script>
import {Overlay, Button, Toast} from 'vant';

import '@/utils/tracking/tracking.js';
import '@/utils/tracking/face-min.js';
export default {
    name: 'faceModal',
    components: {
        [Button.name]: Button,
        [Overlay.name]: Overlay,
        Toast
    },
    props: {
        // visibleModal: {
        //     type: Boolean,
        //     default: true
        // },
        showClose: {
            type: Boolean,
            default: true
        }
    },
    data() {
        return {
            visibleModal1: false,
            isOneself: false,
            programme: true,
            visibleModal: true,
            timer2: null,
            base64: null,
            loading: false,
            faceStuas: null,
            recognitionSuc: false,
            videoEl: {},
            video: null,
            screenshotCanvas: null,
            screenWidth: 300,
            clientHeight: 362,
            uploadLock: true // 上传锁
        };
    },
    watch: {
        visibleModal(newVal, oldVal) {
            if (newVal) {
                this.openModal();
            }
        },
        visibleModal1(val) {
            this.$parent.visibleModal = val;
        }
    },
    mounted() {
        // 是否admin端二维码日程签到
        if (this.$route.params.source === 'admin') {
            this.$axios.get(`/app/api/trainee/user-face-gather/check-user-face`).then(res => {
                if (res.data.code === '200') {
                    this.programmeSign();
                } else {
                    Toast({
                        message: res.data.msg,
                        duration: 3000,
                        forbidClick: true
                    });
                    setTimeout(() => {
                        if (this.$route.query.liveScanning) {
                            this.$router.go(-2);
                        } else {
                            this.$router.replace({path: '/home'});
                        }
                    }, 3000);
                }
            });
        } else {
            this.onself();
        }
        // this.openModal();
    },
    methods: {
        cancelDistinguish() {
            this.visibleModal1 = false;
            this.closeCamera();
            if (this.$route.query.liveScanning) {
                this.$router.go(-2);
            } else {
                this.$router.replace({path: '/home'});
            }
        },
        // 日程是否已签到
        programmeSign() {
            let data = {ilsId: this.$route.params.busId};
            this.$axios.get(`/app/api/trainee/course/checkSignIn`, {
                params: data
            }).then(res => {
                if (res.data.code === '200') {
                    this.isOneself = true;
                    this.programme = true;
                    this.openModal();
                } else {
                    this.programme = false;
                    Toast({
                        message: res.data.msg,
                        duration: 2000,
                        forbidClick: true
                    });
                    setTimeout(() => {
                        if (this.$route.query.liveScanning) {
                            this.$router.go(-2);
                        } else {
                            this.$router.replace({path: '/home'});
                        }
                    }, 3000);
                }
            });
        },
        // 是否本人扫码进行人脸识别
        onself() {
            let data = {usrEntId: this.$route.params.itmId};
            this.$axios.get(`/app/api/trainee/user-face-gather/confirm-user-info`, {
                params: data
            }).then(res => {
                if (res.data.code === '200') {
                    this.isOneself = true;
                    // 是否日程签到
                    if (this.$route.params.userFaceTypeEnum === 'SCHEDULE_FACE') {
                        this.programmeSign();
                    } else {
                        this.openModal();
                    }
                } else {
                    this.isOneself = false;
                    Toast({
                        message: res.data.msg,
                        duration: 3000,
                        forbidClick: true
                    });
                    setTimeout(() => {
                        if (this.$route.query.liveScanning) {
                            this.$router.go(-2);
                        } else {
                            this.$router.replace({path: '/home'});
                        }
                    }, 3000);
                }
            });
        },
        // 重新识别
        reIdentification() {
            this.openModal();
        },
        // 关闭摄像头
        closeCamera() {
            if (!this.visibleModal) return;
            if (typeof window.stream === 'object') {
                if (this.videoEl.srcObject) {
                    this.videoEl.srcObject = null;
                }
                window.stream.getTracks().forEach((track) => track.stop()); // 停止侦测
            }
            if (this.video.srcObject) {
                this.video.srcObject.getTracks()[0].stop();
            }
            if (this.trackerTask) {
                this.trackerTask.stop();
            }
        },
        screenshotAndUpload(context, canva) {
            // 上锁避免重复发送请求
            this.uploadLock = false;
            // 绘制当前帧图片转换为base64格式
            const canvas = this.screenshotCanvas;
            const video = this.video;
            const ctx = canvas.getContext('2d');
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
            const base64Img = canvas.toDataURL('image/jpeg');
            this.loading = true;
            this.closeCamera();
            // 使用 base64Img 请求接口即可
            console.log(this.$route.params, 'this.$route.params');
            let data = {
                ufgPath: base64Img,
                busId: this.$route.params.busId,
                userFaceTypeEnum: this.$route.params.userFaceTypeEnum,
                firIdentificationWay: this.$route.params.firIdentificationWay
            };
            context.clearRect(0, 0, canva.width, canva.height);
            this.$axios.post(`/app/api/trainee/user-face-gather/compareFaceFeature`, data).then(res => {
                this.loading = false;
                this.uploadLock = true;
                if (res.data) {
                    this.recognitionSuc = false;
                    this.visibleModal = false;
                    Toast({
                        message: this.$t('face_sign_success'),
                        duration: 5000,
                        forbidClick: true
                    });
                    if (this.$route.query.liveScanning) {
                        this.$router.go(-2);
                    } else {
                        this.$router.replace({path: '/home'});
                    }
                } else {
                    this.recognitionSuc = true;
                }
            }).catch((err) => {
                this.$emit('takingError');
                this.loading = false;
                this.uploadLock = true;
                Toast({
                    message: this.$t('face_tips2'),
                    duration: 5000,
                    forbidClick: true
                });
                if (this.$route.query.liveScanning) {
                    this.$router.go(-2);
                } else {
                    this.$router.replace({path: '/home'});
                }
                console.log(err);
            });
        },
        openModal() {
            this.isReadyFace = true;
            this.faceStuas = null;
            this.faceModal();
            if (!this.showClose) {
                this.timer2 = setTimeout(() => {
                    this.$emit('cancelFace', true);
                    clearTimeout(this.timer2);
                    this.timer2 = null;
                }, 120000);
            }
        },
        faceModal() {
            if (this.trackerTask) {
                this.closeCamera();
            }
            this.$nextTick(() => {
                this.video = document.getElementById('video');
                this.screenshotCanvas = document.getElementById('screenshotCanvas');
                const canvas = document.getElementById('canvas');
                const context = canvas.getContext('2d');
                // 固定写法
                /*eslint-disable */
                const tracker = new tracking.ObjectTracker('face');//检测人脸
                tracker.setInitialScale(4);
                tracker.setStepSize(2);
                tracker.setEdgesDensity(0.1);
                // 取消第三个参数camera：true，防止闪屏
                this.trackerTask = tracking.track('#video', tracker, { });
                this.videoEl.srcObject = window.stream;
                const constraints = {
                    video: { width: this.screenWidth, height: this.clientHeight, facingMode: 'user' }
                };
                const promise = navigator.mediaDevices.getUserMedia(constraints); // h5 新的API
                const _this = this;
                promise.then(function(MediaStream) {
                    _this.video.srcObject = MediaStream;
                    _this.video.play();
                }).catch(function(PermissionDeniedError) {
                });
                tracker.on('track', function(event) {
                    // 检测出人脸 绘画人脸位置
                    event.data.forEach(function(rect) {
                        context.clearRect(0, 0, canvas.width, canvas.height);
                        context.strokeStyle = '#0764B7';
                        context.strokeRect(rect.x, rect.y, rect.width, rect.height);
                        // 上传图片
                        setTimeout(()=>{
                          _this.uploadLock && _this.screenshotAndUpload(context,canvas);
                        },600)
                    });
                });
            });
        }
    },
    beforeDestroy() {
        this.closeCamera();
    }
};
</script>

<style lang="less" scoped>
/deep/.face-class .el-dialog__body {
  padding: 10px !important;
}
/deep/.van-button--primary{
    background-color: #1989FA;
    border: 1px solid #1989FA;
    padding: 0 40px;
    text-align: center;
}
.overlay{
  z-index: 999;
}
 /* 绘图canvas 不需显示隐藏即可 */
#screenshotCanvas{
  display: none;
}
.video-box{
  background: #000;
  position: relative;
  width: 440px;
  height: 452px;
}
video,canvas{
  position: absolute;
  top: 0;
  left: 0;
  // border: #000000 5px solid;
}
.title{
    height: 36px;
    background-color: #F2F2F2;
    line-height: 36px;
    text-align: center;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
}
</style>
